<!--
 * @Author: 杨伟韦
 * @Date: 2023-04-06 22:26:57
 * @LastEditors: 杨伟韦
 * @LastEditTime: 2024-10-07 17:15:32
 * @Description: 扣人像
-->

<template>
  <div v-if="isOne && type === 'image'" class="attr-item-box">
    <div class="bg-item">
      <Button @click="remove" type="text" long>{{ $t('removeBackground') }}</Button>
    </div>
  </div>
</template>

<script setup name="RemoveBackground">
import useSelect from '@/hooks/select';
import { removeBackground } from '@imgly/background-removal';

import { Utils } from '@kuaitu/core';

const update = getCurrentInstance();
const { canvasEditor, isOne } = useSelect();
const type = ref('');

// 替换图片
const remove = async () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  console.log(activeObject);
  if (activeObject && activeObject.type === 'image') {
    const imageUrl = activeObject.getSrc();
    console.log(imageUrl);

    if (!imageUrl) return;
    let image = await removeBackground(imageUrl);
    let url = URL.createObjectURL(image);
    console.log(url);

    activeObject.setSrc(url, () => {
      canvasEditor.canvas.renderAll();
    });
    url = null;
    image = null;
  }
};

const init = () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject) {
    type.value = activeObject.type;
    update?.proxy?.$forceUpdate();
  }
};

onMounted(() => {
  canvasEditor.on('selectOne', init);
});

onBeforeUnmount(() => {
  canvasEditor.off('selectOne', init);
});
</script>
<style lang="less" scoped>
.attr-item-box {
  margin-top: 8px;
}
</style>
